package manager.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/pages/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化方法
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        //登录的验证  登录和不登录的区别
        //登录后的账号session中存在LOGINUSER的值
        //获取session对象  从中取LOGINUSER 对应的值  取的到  则为已经登录
        if (req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession session = request.getSession();
            Object obj = session.getAttribute("login_user");
            if (obj!=null){
                chain.doFilter(request,response);
//                System.out.println(1);
            }else {
                String path = request.getContextPath();
                String basePath = request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + path + "/";
//                System.out.println(basePath);
                response.sendRedirect(basePath+"index.html");
            }
        }
    }
    @Override
    public void destroy() {
        //销毁方法
    }
}
